package com.xwli.business.util;

/**
 * @program: springcloud
 * @description:
 * @author: xwli
 * @create: 2022-05-28 19:28
 **/

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @Auther: liyue
 * @Date: 2019/7/25 17:44
 * @Description:
 */
public class ExcelUtil {

    /**
     * 读取Excel
     *
     * @param path
     * @return
     */
    public static List<List<String>> readXls(String path) {
        List<List<String>> list = new LinkedList<>();
        try {
            FileInputStream is = new FileInputStream(path);
            Workbook workbook = WorkbookFactory.create(is);
            //HSSFWorkbook excel = new HSSFWorkbook(is);
            //获取第一个sheet
            //HSSFSheet sheet0 = excel.getSheetAt(0);
            Sheet sheet0 = workbook.getSheetAt(0);
            for (Iterator rowIterator = sheet0.iterator(); rowIterator.hasNext(); ) {
                List<String> params = new LinkedList<>();
                XSSFRow row = (XSSFRow) rowIterator.next();
                for (Iterator iterator = row.cellIterator(); iterator.hasNext(); ) {
                    XSSFCell cell = (XSSFCell) iterator.next();
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    params.add(cell.getStringCellValue());
                }
                list.add(params);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return list;
    }


    /**
     * 获取行对象,不存在则创建
     *
     * @param sheet
     * @param line
     * @return
     */
    private static HSSFRow getRow(HSSFSheet sheet, int line) {
        return sheet.getRow(line) != null ? sheet.getRow(line) : sheet.createRow(line);
    }

}